#!/usr/bin/env node

/**
 * ALYR.NET 智能体启动器
 * 确保每次启动都加载并遵循开发规范
 */

const { aiStartupCheck } = require('../core/ai-rules-checker');
const { startRealTimeMonitor } = require('../core/real-time-monitor');
const UnifiedConfigManager = require('../config/unified-config-manager');
const chalk = require('chalk');
const fs = require('fs-extra');

class AlyrAIBootstrap {
  constructor() {
    this.startTime = Date.now();
  }

  // 🚀 智能体启动流程
  async bootstrap() {
    console.log(chalk.blue.bold('🤖 Builder.Alyr.Net 智能体启动中...'));
    console.log(chalk.gray('=' .repeat(50)));
    
    try {
      // 1. 环境检查
      await this.checkEnvironment();
      
      // 2. 规则加载与验证
      const rulesValid = await this.loadAndValidateRules();
      if (!rulesValid) {
        throw new Error('规则验证失败');
      }
      
      // 3. 启动实时监控
      await this.startMonitoring();
      
      // 4. 显示启动成功信息
      await this.displaySuccessInfo();
      
      return true;
      
    } catch (error) {
      console.error(chalk.red(`❌ 智能体启动失败: ${error.message}`));
      return false;
    }
  }

  // 🔍 环境检查
  async checkEnvironment() {
    console.log(chalk.cyan('🔍 检查环境...'));
    
    // 检查必要目录
    const requiredDirs = [
      '.trae',
      '.trae/rules',
      '.trae/logs'
    ];
    
    for (const dir of requiredDirs) {
      await fs.ensureDir(dir);
    }
    
    // 🆕 检查依赖
    await this.checkDependencies();
    
    console.log(chalk.green('✅ 环境检查完成'));
  }

  // 🆕 检查依赖
  async checkDependencies() {
    console.log(chalk.cyan('📦 检查项目依赖...'));
    
    try {
      const packageJson = await fs.readJSON('package.json');
      const allDeps = {
        ...packageJson.dependencies || {},
        ...packageJson.devDependencies || {}
      };
      
      const missingDeps = [];
      
      // CLI 工具列表 - 这些工具需要特殊检查方式
        const cliTools = ['prisma', '@nestjs/cli'];
        const path = require('path');
        
        for (const depName of Object.keys(allDeps)) {
          let isInstalled = false;
          
          if (cliTools.includes(depName)) {
            // 对于 CLI 工具，检查可执行文件是否存在
            if (depName === 'prisma') {
              const prismaPath = path.join(process.cwd(), 'node_modules', 'prisma', 'build', 'index.js');
              isInstalled = fs.existsSync(prismaPath);
            } else if (depName === '@nestjs/cli') {
              const nestPath = path.join(process.cwd(), 'node_modules', '@nestjs', 'cli');
              isInstalled = fs.existsSync(nestPath);
            }
          } else if (depName.startsWith('@types/')) {
            // 对于 @types/* 包，检查类型定义文件是否存在
            const typesPath = path.join(process.cwd(), 'node_modules', depName, 'index.d.ts');
            isInstalled = fs.existsSync(typesPath);
          } else {
            // 对于普通模块，使用 require.resolve
            try {
              require.resolve(depName);
              isInstalled = true;
            } catch (error) {
              isInstalled = false;
            }
          }
          
          if (!isInstalled) {
            missingDeps.push(depName);
          }
        }
      
      if (missingDeps.length > 0) {
        console.log(chalk.yellow(`⚠️  发现 ${missingDeps.length} 个缺失依赖:`));
        missingDeps.forEach(dep => {
          console.log(chalk.red(`   ❌ ${dep}`));
        });
        
        console.log(chalk.blue('🚀 正在自动安装缺失依赖...'));
        
        // 自动安装缺失依赖
        await this.installMissingDependencies();
        
        console.log(chalk.green('✅ 依赖安装完成，重新检查...'));
        
        // 重新检查依赖
        const stillMissingDeps = [];
        for (const depName of Object.keys(allDeps)) {
          let isInstalled = false;
          
          if (cliTools.includes(depName)) {
            // 对于 CLI 工具，检查可执行文件是否存在
            if (depName === 'prisma') {
              const prismaPath = path.join(process.cwd(), 'node_modules', 'prisma', 'build', 'index.js');
              isInstalled = fs.existsSync(prismaPath);
            } else if (depName === '@nestjs/cli') {
              const nestPath = path.join(process.cwd(), 'node_modules', '@nestjs', 'cli');
              isInstalled = fs.existsSync(nestPath);
            }
          } else if (depName.startsWith('@types/')) {
            // 对于 @types/* 包，检查类型定义文件是否存在
            const typesPath = path.join(process.cwd(), 'node_modules', depName, 'index.d.ts');
            isInstalled = fs.existsSync(typesPath);
          } else {
            // 对于普通模块，使用 require.resolve
            try {
              require.resolve(depName);
              isInstalled = true;
            } catch (error) {
              isInstalled = false;
            }
          }
          
          if (!isInstalled) {
            stillMissingDeps.push(depName);
          }
        }
        
        if (stillMissingDeps.length > 0) {
          console.log(chalk.red(`❌ 仍有 ${stillMissingDeps.length} 个依赖安装失败:`));
          stillMissingDeps.forEach(dep => {
            console.log(chalk.red(`   ❌ ${dep}`));
          });
          console.log(chalk.blue('\n💡 请手动运行以下命令:'));
          console.log(chalk.green('   npm run setup'));
          console.log(chalk.gray('   或联系技术支持: builder@alyr.net'));
          
          throw new Error('部分依赖安装失败，请手动安装');
        }
      }
      
      // 🔥 检查并安装 TypeScript 依赖
      await this.checkAndInstallTypescriptDeps();
      
      console.log(chalk.green('✅ 所有依赖已安装'));
      
    } catch (error) {
      if (error.message.includes('依赖') && error.message.includes('失败')) {
        throw error;
      }
      console.log(chalk.yellow('⚠️  依赖检查跳过（可能在开发环境）'));
    }
  }

  // 🚀 安装缺失依赖
  async installMissingDependencies() {
    const { spawn } = require('child_process');
    
    return new Promise((resolve, reject) => {
      console.log(chalk.blue('   执行: npm install --include=dev'));
      
      const installProcess = spawn('npm', ['install', '--include=dev'], {
        stdio: 'inherit',
        shell: true
      });
      
      installProcess.on('close', (code) => {
        if (code === 0) {
          console.log(chalk.green('✅ npm install --include=dev 执行完成'));
          resolve();
        } else {
          console.log(chalk.yellow('⚠️  npm install --include=dev 失败，尝试 npm run setup...'));
          
          // 如果 npm install 失败，尝试 npm run setup
          const setupProcess = spawn('npm', ['run', 'setup'], {
            stdio: 'inherit',
            shell: true
          });
          
          setupProcess.on('close', (setupCode) => {
            if (setupCode === 0) {
              console.log(chalk.green('✅ npm run setup 执行完成'));
              resolve();
            } else {
              console.log(chalk.yellow('⚠️  npm run setup 失败，尝试强制重新安装...'));
              
              // 最后尝试强制重新安装
              const forceProcess = spawn('npm', ['install', '--force', '--include=dev'], {
                stdio: 'inherit',
                shell: true
              });
              
              forceProcess.on('close', (forceCode) => {
                if (forceCode === 0) {
                  console.log(chalk.green('✅ 强制安装成功'));
                  resolve();
                } else {
                  console.log(chalk.red('❌ 依赖安装失败'));
                  reject(new Error('依赖安装失败'));
                }
              });
              
              forceProcess.on('error', (error) => {
                console.log(chalk.red(`❌ 强制安装过程出错: ${error.message}`));
                reject(error);
              });
            }
          });
          
          setupProcess.on('error', (error) => {
            console.log(chalk.red(`❌ setup 过程出错: ${error.message}`));
            reject(error);
          });
        }
      });
      
      installProcess.on('error', (error) => {
        console.log(chalk.red(`❌ 安装过程出错: ${error.message}`));
        reject(error);
      });
    });
  }

  // 🔥 检查并安装 TypeScript 依赖
  async checkAndInstallTypescriptDeps() {
    console.log(chalk.cyan('🔍 检查 TypeScript 依赖...'));
    
    const requiredTypeDeps = [
      '@types/express',
      '@types/node', 
      '@types/react',
      '@types/react-dom'
    ];
    
    const missingTypeDeps = [];
    
    for (const dep of requiredTypeDeps) {
      try {
        require.resolve(dep);
      } catch (error) {
        missingTypeDeps.push(dep);
      }
    }
    
    if (missingTypeDeps.length > 0) {
      console.log(chalk.yellow(`⚠️  发现 ${missingTypeDeps.length} 个缺失的 TypeScript 类型依赖:`));
      missingTypeDeps.forEach(dep => {
        console.log(chalk.red(`   ❌ ${dep}`));
      });
      
      console.log(chalk.blue('🚀 正在自动安装缺失的 TypeScript 依赖...'));
      
      const { spawn } = require('child_process');
      const installCommand = `npm install --save-dev ${missingTypeDeps.join(' ')}`;
      
      return new Promise((resolve, reject) => {
        const installProcess = spawn('npm', ['install', '--save-dev', ...missingTypeDeps], {
          stdio: 'inherit',
          shell: true
        });
        
        installProcess.on('close', (code) => {
          if (code === 0) {
            console.log(chalk.green('✅ TypeScript 依赖安装完成'));
            resolve();
          } else {
            console.log(chalk.red('❌ TypeScript 依赖安装失败'));
            reject(new Error('TypeScript 依赖安装失败'));
          }
        });
        
        installProcess.on('error', (error) => {
          console.log(chalk.red(`❌ 安装过程出错: ${error.message}`));
          reject(error);
        });
      });
    } else {
      console.log(chalk.green('✅ TypeScript 依赖检查完成'));
    }
  }

  // 📋 加载并验证规则
  async loadAndValidateRules() {
    console.log(chalk.cyan('📋 加载 Builder.Alyr.Net 开发规范...'));
    
    // 执行规则检查
    const isValid = await aiStartupCheck();
    
    if (isValid) {
      console.log(chalk.green('✅ 规则加载完成'));
      return true;
    } else {
      console.log(chalk.red('❌ 规则验证失败'));
      return false;
    }
  }

  // 🔍 启动监控
  async startMonitoring() {
    console.log(chalk.cyan('🔍 启动实时规则监控...'));
    
    // 启动实时监控（后台运行）
    startRealTimeMonitor();
    
    console.log(chalk.green('✅ 实时监控已启动'));
  }

  // 🎉 显示启动成功信息
  async displaySuccessInfo() {
    const duration = Date.now() - this.startTime;
    
    // 读取当前配置
    const configManager = new UnifiedConfigManager();
    const config = configManager.config;
    
    console.log(chalk.gray('=' .repeat(50)));
    console.log(chalk.green.bold(`🎉 ${config.project.displayName} 智能体启动成功！${config.project.version}`));
    console.log(chalk.gray(`⏱️ 启动耗时: ${duration}ms`));
    console.log(chalk.gray(`📅 启动时间: ${new Date().toLocaleString()}`));
    
    console.log(chalk.blue('\n📋 当前激活的规则:'));
    
    // 文件命名规则
    const fileNaming = config.developmentStandards?.fileNaming;
    if (fileNaming) {
      console.log(chalk.cyan(`   🔥 后端文件: ${fileNaming.backend?.prefix || 'Alyr-'}前缀 + ${config.developmentStandards?.copyright?.template || '版权声明'}`));
      
      // 解析前端文件命名模板变量
      let frontendPattern = fileNaming.frontend?.pattern || '常规命名';
      if (frontendPattern.includes('{PascalCase}')) {
        frontendPattern = frontendPattern.replace('{PascalCase}', '大驼峰命名');
      } else if (frontendPattern.includes('{camelCase}')) {
        frontendPattern = frontendPattern.replace('{camelCase}', '小驼峰命名');
      } else if (frontendPattern.includes('{kebab-case}')) {
        frontendPattern = frontendPattern.replace('{kebab-case}', '短横线命名');
      }
      
      console.log(chalk.cyan(`   ✅ 前端文件: ${frontendPattern} + ${config.developmentStandards?.componentLibraries?.react || 'React组件库'}`));
    }
    
    // 代码质量规则
    const codeQuality = config.developmentStandards?.codeQuality;
    if (codeQuality) {
      const noAnyType = codeQuality.typescript?.noAnyType ? '禁用any类型' : '允许any类型';
      const securityCall = config.developmentStandards?.apiStandards?.security?.noDirectAxios ? '安全调用' : '常规调用';
      console.log(chalk.cyan(`   🚫 全项目: ${noAnyType} + ${securityCall}`));
    }
    
    // 开发原则
    const minimalChanges = codeQuality?.minimalChanges?.principle || '遵循最小变更原则';
    console.log(chalk.cyan(`   ⚖️ 开发原则: ${minimalChanges} + 精准修改`));
    
    console.log(chalk.blue('\n📞 技术支持:'));
    console.log(chalk.yellow('   🌐 官网: https://gitee.com/Alyr_space/Builder.Alyr.Net'));
    
    console.log(chalk.yellow('\n🤖 智能体已准备就绪，等待任务指令...'));
    console.log(chalk.gray('=' .repeat(50)));
  }

  // 📊 生成启动报告
  async generateStartupReport() {
    const report = {
      timestamp: new Date().toISOString(),
      duration: Date.now() - this.startTime,
      status: 'success',
      rulesLoaded: [
        'user_rules.md',
        'project_rules.md',
        '智能体执行检查清单.md'
      ],
      monitoring: 'active'
    };
    
    await fs.writeJSON('.trae/logs/startup-report.json', report, { spaces: 2 });
  }
}

// 🚀 主启动函数
async function main() {
  const bootstrap = new AlyrAIBootstrap();
  const success = await bootstrap.bootstrap();
  
  if (success) {
    await bootstrap.generateStartupReport();
    
    // 保持进程运行（用于实时监控）
    process.on('SIGINT', () => {
      console.log(chalk.yellow('\n👋 Builder.Alyr.Net 智能体正在关闭...'));
      process.exit(0);
    });
    
  } else {
    process.exit(1);
  }
}

// 导出模块
module.exports = {
  AlyrAIBootstrap,
  main
};

// 如果直接运行此脚本
if (require.main === module) {
  main();
}